package br.com.amigooo.controller;

import br.com.amigooo.Session.UserSession;
import br.com.amigooo.annotation.Public;
import br.com.amigooo.model.User;
import br.com.amigooo.repository.UserImpl;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;

@Resource
public class LoginController {
    
	private Result result;
    private UserSession userSession;
    private UserImpl userImpl;
	
    public LoginController(Result result, UserSession userSession) {
        this.result = result;
        this.userSession = userSession;
        this.userImpl = new UserImpl();
    }
    
    @Public
	@Path("/")
	public void index(){
		
	}

	@Public
    @Post()
    public void auth(User userLogin) {
        User user = userImpl.getUserAuth(userLogin.getEmail(), userLogin.getUserPassword());

        if (user != null) {
            userSession.setUser(user);

            result.redirectTo(HomeController.class).start();
        } else {
            result.include("error", "<div class=\"alert fade in alert-error error-login\">" +
            		"<button type=\"button\" class=\"close\" data-dismiss=\"alert\">×</button>" +
            		"<strong>Erro! </strong>" +
            		"Login ou senha incorreta!</div>").redirectTo(this).index();
        }
    }

    @Get()
    public void logout() {
        userSession.logout();
        result.redirectTo(this).index();
    }
	
}
